﻿Imports SIAVU.Dominio
Imports DevExpress.XtraScheduler
Imports DevExpress.Web.ASPxScheduler
Imports DevExpress.Web.ASPxGridView

Namespace Presentacion
    Partial Public Class ConfirmarTripulantes
        Inherits System.Web.UI.Page

        Private Sub ConfirmarTripulantes_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
            SetearControles()
        End Sub

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        End Sub

#Region "Atributos privados"

        Private strSessionListaUsuariosParaConfirmar As String

#End Region

#Region "Propiedades"

        Public Property ListaUsuariosParaConfirmar() As DataTable
            Get
                strSessionListaUsuariosParaConfirmar = "BORRAR" + Session.SessionID + DirectCast(Me.Page, System.Web.UI.Page).AppRelativeVirtualPath + "ListaUsuariosParaConfirmar"
                Return Session(strSessionListaUsuariosParaConfirmar)
            End Get
            Set(ByVal value As DataTable)
                strSessionListaUsuariosParaConfirmar = "BORRAR" + Session.SessionID + DirectCast(Me.Page, System.Web.UI.Page).AppRelativeVirtualPath + "ListaUsuariosParaConfirmar"
                Session(strSessionListaUsuariosParaConfirmar) = value
            End Set
        End Property

#End Region

#Region "Eventos"

        Protected Sub gvTripulantes_BeforeGetCallbackResult(ByVal sender As Object, ByVal e As EventArgs) Handles gvTripulantes.BeforeGetCallbackResult
            CargarGrillaTripulantes()
        End Sub

        Protected Sub gvTripulantes_RowUpdating(ByVal sender As Object, ByVal e As DevExpress.Web.Data.ASPxDataUpdatingEventArgs) Handles gvTripulantes.RowUpdating
            Try
                If Me.ListaUsuariosParaConfirmar IsNot Nothing Then
                    Dim dr As DataRow = Me.ListaUsuariosParaConfirmar.Rows.Find(e.Keys(0))
                    dr("Observacion") = e.NewValues("Observacion")
                    dr("EstadoActividadFuturo") = e.NewValues("EstadoActividadFuturo")
                    dr("AsignarGuardia") = e.NewValues("AsignarGuardia")
                    dr("Modificada") = DataRowState.Modified
                End If
            Catch ex As Exception
                Throw
            Finally
                gvTripulantes.CancelEdit()
                e.Cancel = True
            End Try

        End Sub

        Protected Sub btnGuardarCambios_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnGuardarCambios.Click
            ConfimarTripulantesSacarGuardia()
        End Sub

        Protected Sub grid_HtmlRowPrepared(ByVal sender As Object, ByVal e As ASPxGridViewTableRowEventArgs)
            Dim hasError As Boolean = e.GetValue("FirstName").ToString().Length <= 1
            hasError = hasError OrElse e.GetValue("LastName").ToString().Length <= 1
            hasError = hasError OrElse Not e.GetValue("Email").ToString().Contains("@")
            hasError = hasError OrElse CInt(Fix(e.GetValue("Age"))) < 18
            Dim arrival As DateTime = CDate(e.GetValue("ArrivalDate"))
            hasError = hasError OrElse DateTime.Today.Year <> arrival.Year OrElse DateTime.Today.Month <> arrival.Month
            If hasError Then
                e.Row.ForeColor = System.Drawing.Color.Red
            End If
        End Sub

        Protected Sub grid_StartRowEditing(ByVal sender As Object, ByVal e As DevExpress.Web.Data.ASPxStartRowEditingEventArgs)
            If (Not gvTripulantes.IsNewRowEditing) Then
                gvTripulantes.DoRowValidation()
            End If
        End Sub

#End Region

#Region "Metodos"

        Public Sub SetearControles()
            '//Inicializo propiedades en ambos controles
            Dim strPeriodo As String = Date.Now.Year.ToString() + "/" + Date.Now.Month.ToString()
            ucPostas1.Periodo = strPeriodo
        End Sub

        Public Sub CargarGrillaTripulantes()
            Try
                If Me.ListaUsuariosParaConfirmar Is Nothing Then
                    Dim oEntityManager As New EntityManager
                    Me.ListaUsuariosParaConfirmar = oEntityManager.GetTripulantesParaConfirmar(Me.ucPostas1.GetPostaIdSeleccionada())
                End If
                gvTripulantes.DataSource = Me.ListaUsuariosParaConfirmar
                gvTripulantes.AutoGenerateColumns = False
                gvTripulantes.DataBind()

            Catch ex As Exception
                'TODO Pagina de error
                Throw
            End Try
        End Sub

        Protected Function GetImageURL(ByVal EstadoActividad As String)
            Select Case EstadoActividad
                Case EEstadoActividad.Confirmada.ToString
                    Return "~/Imagenes/EstadoActividad/ActividadConfirmada.png"
                Case EEstadoActividad.NoConfirmada.ToString
                    Return "~/Imagenes/EstadoActividad/ActividadNoConfirmada.png"
                Case EEstadoActividad.Desconocido.ToString
                    Return "~/Imagenes/EstadoActividad/ActividadDesconocida.png"
                Case EEstadoActividad.Realizado
                    Return "~/Imagenes/EstadoActividad/ActividadConfirmada.png"
                Case EEstadoActividad.NoRealizado
                    Return "~/Imagenes/EstadoActividad/ActividadNoConfirmada.png"
                Case Else
                    Return ""
            End Select
        End Function

        Public Sub LimpiarSession()
            'strSessionListaUsuariosParaConfirmar = Session.SessionID + DirectCast(Me.Page, System.Web.UI.Page).AppRelativeVirtualPath + "ListaUsuariosParaConfirmar"
            'Session(strSessionListaUsuariosParaConfirmar) = Nothing
            Me.ListaUsuariosParaConfirmar = Nothing
        End Sub

        Private Sub ConfimarTripulantesSacarGuardia()
            Try
                Dim oEntityManager As New EntityManager
                If Me.ListaUsuariosParaConfirmar IsNot Nothing AndAlso Me.ListaUsuariosParaConfirmar.Rows.Count > 0 Then
                    oEntityManager.ConfimarTripulantesSacarGuardia(Me.ListaUsuariosParaConfirmar)
                End If
                Me.LimpiarSession()
                Session("MensajeInformacion") = "Se han confirmado los tripulantes de manera exitosa"
                Response.Redirect("MenuPrincipal.aspx", False)

            Catch ex As Exception
                Response.Redirect("_NotificacionDeError.aspx")
            End Try
        End Sub

#End Region

#Region "Validaciones"

        Protected Sub gvTripulantes_RowValidating(ByVal sender As Object, ByVal e As DevExpress.Web.Data.ASPxDataValidationEventArgs) Handles gvTripulantes.RowValidating
            For Each column As GridViewColumn In gvTripulantes.Columns
                Dim dataColumn As GridViewDataColumn = TryCast(column, GridViewDataComboBoxColumn)
                If dataColumn Is Nothing Then
                    Continue For
                End If
                If dataColumn.FieldName = "EstadoActividadFuturo" AndAlso e.NewValues(dataColumn.FieldName) = EEstadoActividad.NoRealizado.ToString Then
                    If e.NewValues("AsignarGuardia") Is Nothing Then
                        e.Errors(gvTripulantes.Columns("AsignarGuardia")) = "Debe seleccionar un tripulante de guardia."
                    Else
                        For Each drAux As DataRow In Me.ListaUsuariosParaConfirmar.Rows
                            If (drAux("AsignarGuardia") = e.NewValues("AsignarGuardia")) AndAlso _
                           (drAux("UsuarioID") <> e.NewValues("UsuarioID")) Then
                                e.Errors(gvTripulantes.Columns("AsignarGuardia")) = "Ya ha seleccionado a este tripulante para cubrir otra guardia."
                            End If
                        Next
                    End If
                    If e.NewValues("Observacion") Is Nothing Then
                        e.Errors(gvTripulantes.Columns("Observacion")) = "Debe ingresar una observación."
                    End If
                End If
            Next column

            If e.Errors.Count > 0 Then
                e.RowError = "Por favor, verifique los errores posicionandose sobre el ícono de error."
            End If
        End Sub

#End Region

    End Class
End Namespace
